var LGL = window.LGL||{};
window.LGL = LGL;

LGL.initSearchFunc = function(){
	var { filter, map, debounceTime, distinctUntilChanged, ajax } = rxjs;
	$.template( "artListTemplate", getArtListTemplate());
	$.template( "artPaginationTemplate", getPaginationTemplate());
	$.template( "searchTitleTemplate", getTitleTemplate());

  var artSearchInput = rxjs.fromEvent(
    document.querySelector('#art-search-input'),
    'input'
  )
	$('#art-search-input').on('focus',function(){
		var value = $(this).val();
		$("#search-input-box").addClass('focus');
		updateDataPannelShowStatus(value);
	}).on('blur',function(){
		var value = $(this).val();
		if(!value || $.trim(value)===''){
			$("#search-input-box").removeClass('focus');
			value = '';
			$(this).val('');
			updateDataPannelShowStatus(value);
		}
	});
	$("#search-input-box .del").on("click",function(){
		$('#art-search-input').val('');
		$('#art-search-input').trigger('blur');
	});
	$("#search-input-box .search").on("click",function(){
		$("#search-input-box").addClass('focus');
	});
  // 过滤掉小于3个字符长度的目标值
  artSearchInput
    .pipe(
      map((event) => event.target.value),
      debounceTime(500),
      distinctUntilChanged()
    )
    .subscribe((value) => {
			updateDataPannelShowStatus(value);
			if(!value || $.trim(value)==='' || $.trim(value).length<=2){
				return;
			}
			var size = $("#art-search-list").data("size") || 24;
			LGL.searchFunc(value,1,size);
    });
};

function updateDataPannelShowStatus(value){
	if(!value || $.trim(value)===''|| $.trim(value).length<=2){
		$(".lgl-content-box").each(function(){
				if($(this).hasClass("search-pannel")){
					$(this).hide();
				}else{
					$(this).show();
				}
		});
		$("#search-input-box .del").hide();
		$("#art-search-title").html('');
		$("#art-search-pagination").html('');
		$("#art-search-list").html(getLoadingTemplate());
		return;
	}else{
		$("#search-input-box .del").show();
		$(".lgl-content-box").each(function(){
				if($(this).hasClass("search-pannel")){
					$(this).show();
				}else{
					$(this).hide();
				}
		});
	}
}

LGL.searchFunc = function(word,page,size){
	var { ajax } = rxjs;
	var URL = 'https://es-api.lglspace.cn/arts';
	if(document.location.href.includes('localhost:')){
		URL = 'http://localhost:8702/arts';
	}
	var config = {
		url: URL,
		method: 'POST',
		headers: {
			'Content-Type': 'application/json',
			Accept: 'application/json:charset=utf-8',
		},
		body: JSON.stringify({
			page: page,
			size: size,
			word: word,
		}),
	}
	$("#art-search-title").html('');
	$("#art-search-pagination").html('');
	$("#art-search-list").html(getLoadingTemplate());
	ajax.ajax(config).subscribe({
		next: (data) => {
			window.console.log(data);
			if(!data.response.datas){
				data.response.datas = [];
			}else{
				data.response.datas.forEach(function(d){
					  if(!d.categories){
							d.categories = [];
						}
						if(!d.tags){
							d.tags = [];
						}
						d.dateStr = LGL.dateFormat("YYYY-mm-dd", new Date(d.date))
				})
			}
			data.response.pageInfo.word = word;
			$( "#art-search-list" ).html($.tmpl("artListTemplate",data.response.datas ));
			var pageObj = $.tmpl("artPaginationTemplate",data.response.pageInfo );
			LGL.initPagination(pageObj);
			$("#art-search-pagination").html(pageObj);
			$( "#art-search-title" ).html($.tmpl("searchTitleTemplate", {word:word,total:data.response.pageInfo.total}));
		},
		error: (err) => {
			window.console.log(err)
		},
		complete: () => {
			console.log('complete')
		},
	});
}

function getArtListTemplate(){
	// return `<span class="update-date">{{html content}}</span>`;
	return `<div class="art-list-item">
		<div class="art-title">
				<a class="title" href="/posts/\${uri}">{{html title}}</a>
		</div>
		<div class="art-meta">
				{{if categories && categories.length>0 }}
				<span class="category">
						{{each(i,cat) categories}}
						<a href="/categories/\${cat}/"> \${cat} </a>
						{{/each}}
				</span>
				{{/if}}

				{{if tags && tags.length>0 }}
				<span class="tag">
					  {{each(i,tag) tags}}
						<a href="/tags/\${tag}/"> \${tag} </a>
						{{/each}}
				</span>
				{{/if}}
				<span class="update-date">\${dateStr}</span>
		</div>
		<div class="art-sumary">
		{{html content}}
		</div>
	</div>`;
}

function getPaginationTemplate(){
	return `<div class="lgl-pagination-box" data-type="search" data-word="\${word}" data-total-length="\${total}" data-item-limit="\${size}" data-current-page="\${page}"></div>`;
}

function getTitleTemplate(){
	return `<div class="art-list-summary">搜索词:<span>\${word}</span>,&nbsp;共搜索到<em>\${total}</em>篇文章</div>`;
}

function getLoadingTemplate(){
	return `<div class="loading"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></div>`;
}

/**
{
      "categories": [
        "java"
      ], 
      "content": "Failed to execute goal org.apache.maven.plugins:maven-war-plugin:2.2:war (default-war) on project stulab-<em>springboot</em>", 
      "date": "2020-11-04T03:30:28.000Z", 
      "draft": false, 
      "tags": [
        "java", 
        "springboot", 
        "tomcat"
      ], 
      "title": "<em>SpringBoot</em>\u5e94\u7528\u5982\u4f55\u6253\u5305\u6210WAR\u5305", 
      "uri": "/java/java-springboot-war"
    }
 */

